import os
import re
import zhconv


def optimize(str_o):
    # 将传入字符串中匹配正则表达式的部分替换成_重复2次，再修整前后多余的_
    regex = re.compile(r"[^\s0-9.A-Za-z\u4E00-\u9FA5\u3040-\u30FF\u31F0-\u31FF-_\n]|_{2,}|\s{2,}|^_|_$|_-_|-_-")
    str_tmp = regex.sub(' ', str_o)  # 将匹配的部分替换为空格
    str_tmp = regex.sub(' ', str_tmp)  # 将多个空格转换为单个
    str_tmp = str_tmp.strip(" ")  # 修整前后空格
    str_tmp = zhconv.convert(str_tmp, "zh-cn")  # 转化为简体中文
    return str_tmp


if __name__ == '__main__':
    print("====去除特殊符号，转为简体字====")
    dir_path = input("输入要修整的目录路径 ")
    if dir_path == "":
        print("无效操作你，空文件名！")
    else:
        fname_list = os.listdir(dir_path)
        count = 0
        for x in fname_list:
            name_tmp = optimize(x)
            old_name = os.path.join(dir_path, x)
            new_name = os.path.join(dir_path, name_tmp)
            if old_name != new_name:
                os.rename(old_name, new_name)
                count += 1
                print(old_name)
        print("修改文件数：" + str(count) + "/" + str(len(fname_list)))
